import tushare as ts
global pro  #在使用前初次声明
ts.set_token('b31e0ac207a5a45e0f7503aff25bf6bd929b88fe1d017a034ee0d530')
pro = ts.pro_api()


def get_ma120():
    hour_start = datetime.now()  # --》用时

    start_time, today_time, today_hour = other.time_start()  # ('20201128', '20201218', '22:11')
    len_time, time_0, time_1 = other.len_fangzhi(start_time, today_time)  # (15, '20201218', '20201217')
    data_get_ts = pro.stock_basic(exchange='', list_status='L',
                                  fields='ts_code,symbol,name,area,industry,list_date').rename(
        columns={'symbol': 'code'})

    list_collect = []
    for szcode in data_get_ts.ts_code[:]:
        ##接口限制访问500次/分钟，加一点微小的延时防止被ban
        # time.sleep(0.121)
        len_time_sz = other.len_fangzhi_szcode(szcode, start_time, today_time)
        if len_time_sz <= len_time - 1:  # 防止出错
            continue
        if today_time != time_0 or (str(datetime.now())[11:13] > str(15)):  # 第二天 or 当日15点以后（）
            listr = other.fc_get(szcode[:6], start_time, time_0,
                                 time_1)  # ['代码', '603992.XSHG', 'fc时间20200325', 20.09, '成交量', 86524.0]
        list_collect.append(listr)
    df_mongo = pd.DataFrame(list_collect)
    #     print(df_mongo)

    df_mongo.to_csv("data_gp/get_ma120.txt", encoding="utf-8")
    columns_name = ["code", "time", "close_yestday", "MA_5", "MA_30", "MA_120", "H_10", "L_10", "MA_C_50"]
    if len(df_mongo.columns) == len(columns_name):
        df_mongo = pd.DataFrame(list_collect, columns=columns_name)
        df_mongo.to_csv("data_gp/get_ma120.txt", encoding="utf-8")

    # --》检查错误2020.12.18
    if len(df_mongo.columns) != len(columns_name):
        print("--->请检查:列数")
    if len(df_mongo) < 3000:
        print("--->请检查:股票数量是否正确")
    arr = data_get_ts.columns.str.contains(
        '^ts_code')  # [False False False False False False False False False False False False False False False False]
    #     print('True个数：',np.sum(arr!=0))
    #     print('False个数：',np.sum(arr==0))
    if np.sum(arr != 0) == 0:
        print("--->请检查:获取数量为空")
        data_get_ts = pro.stock_basic(exchange='', list_status='L',
                                      fields='ts_code,symbol,name,area,industry,list_date').rename(
            columns={'symbol': 'code'})
        print(data_get_ts)
    # --》用时
    hour_end = datetime.now()
    print("MA120用时{}".format((hour_end - hour_start)))
    return df_mongo